using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace PeDALS.Tools.AZ.PSTArchive
{
    public partial class LogEntryDisplay : Form
    {
        private List<LogEntry> mlleExtractionLog;
        private string mstrExportRootFolder;

        public bool Save
        {
            set
            {
                btnSaveLog.Enabled = value;
            }
        }

        public List<LogEntry> ExtractionLog
        {
            set 
            {
                mlleExtractionLog = value;
                if (cbLogLevel.Items.Count > 0)
                {
                    LoadLogData((LogEntryType)cbLogLevel.SelectedIndex);
                }
            }
        }

        public LogEntryDisplay(string strExportRootFolder) : this()
        {
            mstrExportRootFolder = strExportRootFolder;
        }

        private LogEntryDisplay()
        {
            InitializeComponent();
        }

        private void LogEntryDisplay_Load(object sender, EventArgs e)
        {
            cbLogLevel.Items.AddRange(Enum.GetNames(typeof(LogEntryType)));
            cbLogLevel.SelectedIndex = (int) LogEntryType.Log;
            LoadLogData((LogEntryType)cbLogLevel.SelectedIndex);
        }

        private void LoadLogData(LogEntryType letLevel)
        {
            List<LogEntry> lleExtractionLogView = mlleExtractionLog.FindAll(delegate(LogEntry leFoundLogEntry) { return leFoundLogEntry.EntryType >= letLevel; });
            dgvLogViewer.DataSource = lleExtractionLogView;
        }

        private void cbLogLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadLogData((LogEntryType)cbLogLevel.SelectedIndex);
        }

        private void btnSaveLog_Click(object sender, EventArgs e)
        {
            try
            {
                // Create an instance of the XmlSerializer class.
                XmlSerializer xsSerializer = new XmlSerializer(typeof(List<LogEntry>));

                string strFilename = string.Format("{0}\\{1}{2:yyyyMMddHHmmss}.xml", mstrExportRootFolder, (LogEntryType)cbLogLevel.SelectedIndex, DateTime.Now);
                // Writing the file requires a StreamWriter.
                StreamWriter swWriter = new StreamWriter(strFilename);

                // Serialize the class, and close the StreamWriter.
                xsSerializer.Serialize(swWriter, (List<LogEntry>)dgvLogViewer.DataSource);
                swWriter.Close();
                MessageBox.Show(string.Format("Log file {0} saved", strFilename),this.Text);
            }
            catch (Exception eException)
            {
                MessageBox.Show(string.Format("Error:  Saving log file failed as a result of {0}", eException.Message), this.Text);
            }
        }
    }
}